/*
 * @Author: 哈尔滨大拐 3181845089@qq.com
 * @Date: 2022-07-19 20:40:47
 * @LastEditors: 哈尔滨大拐 3181845089@qq.com
 * @LastEditTime: 2022-07-21 10:36:16
 * @FilePath: \mygit\实验\购物车\script2.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const productData = [
    {
        id: 1001,
        imgUrl: "./imgs/apple.png",
        title: "苹果",
        titleEn: "Apple",
        price: 2.99,
    },
    {
        id: 1002,
        imgUrl: "./imgs/beer.png",
        title: "啤酒",
        titleEn: "Bee",
        price: 14.99,
    },
    {
        id: 1003,
        imgUrl: "./imgs/milk.png",
        title: "牛奶",
        titleEn: "Milk",
        price: 4.99,
    },
    {
        id: 1004,
        imgUrl: "./imgs/doughnut.png",
        title: "甜甜圈",
        titleEn: "Doughnut",
        price: 19.99,
    },
    {
        id: 1005,
        imgUrl: "./imgs/bread.png",
        title: "面包",
        titleEn: "Bread",
        price: 3.99,
    },
    {
        id: 1006,
        imgUrl: "./imgs/aubergine.png",
        title: "茄子",
        titleEn: "Aubergine",
        price: 3.49,
    },
    {
        id: 1007,
        imgUrl: "./imgs/lettuce.png",
        title: "生菜",
        titleEn: "Lettuce",
        price: 2.99,
    },
    {
        id: 1008,
        imgUrl: "./imgs/flour.png",
        title: "谷物",
        titleEn: "Flour",
        price: 17.99,
    },
]


let productList = document.querySelector("#product-list")
let cartList = document.querySelector("#cart-list")
let totalPrice = document.querySelector(".total .price")

// 生成商品
productData.forEach((product) => {
    let li = document.createElement("li")
    li.innerHTML = `
    <img src="${product.imgUrl}" alt="">
        <h4>${product.title}</h4>
        <h5>${product.titleEn}</h5>
        <h6>¥${product.price}</h6>
        <button prod-id='${product.id}'>加入购物车</button>
    `;
    li.prod = product
    productList.appendChild(li)
})

let cookieData = getCookie("cartData")
const cartData = cookieData ? JSON.parse(cookieData) : []


cartData.forEach((product) => {
    insertLiToCart(product)
})

calcTotalPrice()

// 利用事件委托将购物车的点击事件绑定给product-list
productList.addEventListener("click", (e) => {
    let target = e.target
    if (target.tagName === "BUTTON") {
        let product = target.parentNode.prod
        product.quantity = product.quantity || 1;


        let productFromCart = cartData.find((element) => {
            return element.id == product.id
        })

        if (productFromCart) {
            productFromCart.quantity++
            let quantityInput = productFromCart.dom.querySelector('.quantity-input')
            quantityInput.value = productFromCart.quantity
        } else {
            insertLiToCart(product)
            cartData.push(product)
            setCookie('cartData', JSON.stringify(cartData))
        }
    }
    calcTotalPrice()
})

// 向cartList中插入li
function insertLiToCart(product) {
    let li = document.createElement("li")
    li.innerHTML = `
    <div class="item">
        <img src="${product.imgUrl}" alt="">
        <p>${product.title}</p>
    </div>
    <div class="price">
        <p>¥${product.price}</p>
    </div>
    <div class="quantity">
        <input type="number" id="${product.id}" class="quantity-input" value="${product.quantity}">
    </div>
    <div class="delete">
        <button class="btn-delete" data-id="${product.id}">X</button>
    </div>
    `
    cartList.appendChild(li)
    product.dom = li
}

// quantity输入框的input事件
cartList.addEventListener('input', (e) => {
    let target = e.target
    if (target.className == "quantity-input") {
        cartData.map((product) => {
            if (product.id == target.id) {
                product.quantity = target.value;
            }
        });

        setCookie("cartData", JSON.stringify(cartData))
        calcTotalPrice()
    }
}, false)


// 总价钱
function calcTotalPrice() {
    let result = 0
    cartData.forEach((product) => {
        result += product.price * product.quantity
    })
    totalPrice.innerHTML = "$" + result
}


// 删除
cartList.addEventListener("click", function (e) {
    const target = e.target
    if (target.className == 'btn-delete') {
        if (confirm("确定删除吗？")) {
            let index = cartData.findIndex((product) => {
                return product.id = target.dataset.id
            })
            cartData.splice(index, 1)
            target.parentNode.parentNode.remove()
            setCookie("cartData", JSON.stringify(cartData));
            calcTotalPrice();
        }
    }
})